import { t } from "@/utils/i18n";
import { Form, FormInstance, Input, Select } from "antd";
import {
  ForwardRefRenderFunction,
  forwardRef,
  useImperativeHandle,
  useMemo,
} from "react";

import { useRequest } from "@/hooks/use-request";
import { antdUtils } from "@/utils/antd";
import { Role } from "../role/service";
import Avatar from "./avatar";
import userService, { User } from "./service";

interface PropsType {
  open: boolean;
  editData?: any;
  onSave: () => void;
  setSaveLoading: (loading: boolean) => void;
}

const NewAndEditForm: ForwardRefRenderFunction<FormInstance, PropsType> = (
  { editData, onSave, setSaveLoading },
  ref
) => {
  const [form] = Form.useForm();
  const { runAsync: updateUser } = useRequest(userService.updateUser, {
    manual: true,
  });
  const { runAsync: addUser } = useRequest(userService.addUser, {
    manual: true,
  });
  const { data: roles, loading: getRolesLoading } = useRequest(
    userService.getRoles
  );

  useImperativeHandle(ref, () => form, [form]);

  const finishHandle = async (values: User) => {
    setSaveLoading(true);

    if (values?.avatar?.[0]?.response?.id) {
      values.avatar = values?.avatar?.[0]?.response?.id;
    } else {
      values.avatar = null;
    }

    if (editData) {
      const [error] = await updateUser({ ...editData, ...values });
      setSaveLoading(false);
      if (error) {
        return;
      }
      antdUtils.message?.success(t("NfOSPWDa" /* 更新成功！ */));
    } else {
      const [error, data] = await addUser(values);
      setSaveLoading(false);
      if (error) {
        return;
      }
      antdUtils.modal?.success({
        title: t("JANFdKFM" /* 创建成功！ */),
        content: `${(data as any).nickName}的密码是\r\n${
          (data as any).password
        }`,
        onOk: () => {},
      });
    }

    onSave();
  };

  const initialValues = useMemo(() => {
    if (editData) {
      return {
        ...editData,
        avatar: editData.avatarEntity
          ? [
              {
                uid: "-1",
                name: editData.avatarEntity.fileName,
                states: "done",
                url: editData.avatarEntity.filePath,
                response: {
                  id: editData.avatarEntity.id,
                },
              },
            ]
          : [],
        roleIds: (editData.roles || []).map((role: Role) => role.id),
      };
    }
  }, [editData]);

  return (
    <Form
      labelCol={{ sm: { span: 24 }, md: { span: 5 } }}
      wrapperCol={{ sm: { span: 24 }, md: { span: 16 } }}
      form={form}
      onFinish={finishHandle}
      initialValues={initialValues || { sex: 1 }}
    >
      <Form.Item label="头像" name="avatar">
        <Avatar />
      </Form.Item>
      <Form.Item
        label={t("qYznwlfj" /* 用户名 */)}
        name="userName"
        rules={[
          {
            required: true,
            message: t("jwGPaPNq" /* 不能为空 */),
          },
        ]}
      >
        <Input disabled={!!editData} />
      </Form.Item>
      <Form.Item
        label={t("rnyigssw" /* 昵称 */)}
        name="nickName"
        rules={[
          {
            required: true,
            message: t("iricpuxB" /* 不能为空 */),
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item label="角色" name="roleIds">
        <Select
          options={(roles || []).map((role) => ({
            label: role.name,
            value: role.id,
          }))}
          mode="multiple"
          loading={getRolesLoading}
        />
      </Form.Item>
    </Form>
  );
};

export default forwardRef(NewAndEditForm);
